import pymysql
class Pattern:
    def __init__(self, database: str, user: str, password: str, host: str = 'localhost', port: int = 3306, charset: str = 'utf8'):
        self.db = pymysql.connect(
            database=database,
            user=user,
            password=password,
            host=host,
            port=port,
            charset=charset
        )

    def insert(self, table: str, values: tuple, columns: str = ''):
        try:
            with self.db.cursor() as cursor:
                if columns == '':
                    sql = f'insert into {table} values {values}'
                else:
                    sql = f'insert into {table} ({columns}) values {values}'
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print("数据库操作异常")

    def delete(self, table: str, where: str):
        try:
            with self.db.cursor() as cursor:
                sql = f'delete form {table} where {where}'
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print("数据库操作异常")

    def update(self, table: str, columns: str, values: str, where: str):
        try:
            with self.db.cursor() as cursor:
                sql = f'update {table} set {zip(columns, values)} where {where}'
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print("数据库操作异常")

    def select(self, table: str, columns: str = '*', where: str = '1 == 1'):
        try:
            with self.db.cursor() as cursor:
                sql = f'select {columns} form {table} where {where}'
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print("数据库操作异常")

    def __del__(self):
        self.db.close()
